import json
import math
import random
import re
import subprocess
import time
from functools import partial #用来固定某个参数的固定值

import ddddocr

subprocess.Popen=partial(subprocess.Popen,encoding='utf-8')
import execjs
import requests

def get_number():
    one = random.randint(1, 2)
    if one == 1:
        two = random.randint(5, 9)
        three = random.randint(4,9)
        four = random.randint(1,6)
    else:
        two = random.randint(1, 5)
        three = random.randint(3, 9)
        four = random.randint(1, 8)
    return int(str(one)+str(two)+str(three)+str(four))
def get_EE_ML(slide_track_windth,str):
    with open('./数美滑块-轨迹加密.js','r',encoding='utf-8') as f:
        js_code = f.read()
    return execjs.compile(js_code).call('_0x51d516',slide_track_windth,str)
def getcaptchaUuid():
    with open('./数美滑块.js','r',encoding='utf-8') as f:
        js_code = f.read()
    return execjs.compile(js_code).call('_0x1b55e2')
def get_slide_img():

    url = "https://captcha1.fengkongcloud.cn/ca/v1/register"
    params = {
        "channel": "DEFAULT",
        "rversion": "1.0.4",
        "organization": "d6tpAY1oV0Kv5jRSgxQr",
        "appId": "default",
        "lang": "zh-cn",
        "callback": "sm_1697275737983",
        "data": "^%^7B^%^7D",
        "model": "slide",
        "captchaUuid": uuid,
        "sdkver": "1.1.3"
    }
    response = sess.get(url, params=params)

    data = json.loads(re.findall('\((.*?)\)',response.text)[0])
    return data
def save_img(data):
    bg = 'https://castatic.fengkongcloud.cn' + data['detail']['bg']
    fg = 'https://castatic.fengkongcloud.cn'+data['detail']['fg']
    with open('../static/bg.jpg','wb') as f:
        f.write(requests.get(url = bg).content)
    with open('../static/fg.png', 'wb') as f:
        f.write(requests.get(url = fg).content)
    print('滑块图片保存成功！')
def getSeild():
    ocr = ddddocr.DdddOcr(det=False,ocr=False,show_ad=False)
    with open('../static/bg.jpg','rb') as f:
        bg = f.read()
    with open('../static/fg.png', 'rb') as f:
        fg = f.read()
    target = ocr.slide_match(bg,fg,simple_target=True)
    return target
def __ease_out_expo(sep):
    if sep == 1:
        return 1
    else:
        return 1 - pow(2,-10*sep)
def get_slide_track(distance):
        if not isinstance(distance, int) or distance < 0:
            raise ValueError(f"distance类型必须是大于等于0的整数: distance: {distance}, type: {type(distance)}")
        # 初始化轨迹列表
        slide_track = [
            [0, 0, 0],
        ]
        # 共记录count次滑块位置信息
        count = random.randint(20, 30) + random.randint(5, 10)
        # 初始化滑动时间
        t = 0
        # 记录上一次滑动的距离
        _x = 0
        _y = 0
        for i in range(count):
            # 已滑动的横向距离
            x = round(__ease_out_expo(i / count) * distance)
            if x == _x:
                continue
                # 滑动过程消耗的时间
            t += (100 + random.randint(3,8))
            slide_track.append([x, _y, t])
            _x = x
        slide_track.append(slide_track[-1])
        zs = random.randint(8, 10)
        y = [random.randint(2,4)] + [random.randint(5,7) for i in range(random.randint(2,3))] + [zs for i in range(random.randint(15,19))]
        if len(y) < len(slide_track) - 1:
            y = y + [zs for i in range(len(slide_track) - len(y))]
        else:
            y = y[:len(slide_track) - 1]
        y = sorted(y)
        for i in range(1,len(slide_track)):
            slide_track[i][1] = y[i-1]
        return slide_track

def fverify():
    # 获取滑块图片信息
    data = get_slide_img()
    # 保存图片
    save_img(data)
    # 滑块距离对比缩放  x
    target = round(getSeild()['target'][0] * (300 / 600))
    # 滑块轨迹
    slide_track = get_slide_track(target)

    url = "https://captcha1.fengkongcloud.cn/ca/v2/fverify"
    params = {
        "us": "Eqnlw9jmiok=",
        "ma": "Ku1yrQmmWo8=",
        "protocol": "179",
        "rid": data['detail']['rid'],
        "organization": "d6tpAY1oV0Kv5jRSgxQr",
        "ee": get_EE_ML(slide_track,"1822c58f"),
        "xc": "MPQBHp3MK74=",
        "ostype": "web",
        "qu": "Q/IW6xhk8TI=",
        "ml": get_EE_ML(target/300,"2a29ac9a"),
        "sdkver": "1.1.3",
        "hd": "w6ArMUdGI6s=",
        "rversion": "1.0.4",
        "jv": "tnws0FUkt6c=",
        "captchaUuid": uuid,
        "jn": "w6ook9DZFNo=",
        "ra": get_EE_ML(get_number(),"3126130b"),
        "xy": "xIAv2QAUoJA=",
        "callback": "sm_"+str(math.ceil(time.time() * 1000)),
        "act.os": "web_pc",
        "rj": "LpMN9yrHH3I="
    }

    time.sleep(5)
    response = sess.get(url, params=params)

    print(response.text)

if __name__ == '__main__':
    sess = requests.session()

    sess.headers = {
        "Accept": "*/*",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Origin": "https://console.ishumei.com",
        "Pragma": "no-cache",
        "Referer": "https://console.ishumei.com/",
        "Sec-Fetch-Dest": "script",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "cross-site",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.47",
        "sec-ch-ua": "^\\^Microsoft",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "^\\^Windows^^"
    }
    for i in range(10):
        uuid = getcaptchaUuid()
        fverify()
